<template>
  <div>
    <div class="fields">
      <div class="center gap-4">
        <a-button v-if="recycleBin.length > 0" @click="recoverField">
          <template #icon>
            <PlusOutlined />
          </template>
          {{ t('Recover field') }}
        </a-button>
        <a-button v-if="form?.type === 'FILE'" @click="addField">
          {{ t('Add field') }}
          <template #icon>
            <PlusOutlined />
          </template>
        </a-button>
        <a-button @click="clear">{{ t('Clear all') }}</a-button>
      </div>
      <div class="grid grid-cols-3 mt-16">
        <div class="title">{{ t('Customer field') }}</div>
        <div class="title">{{ t('My field') }}</div>
        <div class="title"></div>
      </div>
      <!--  -->
      <div class="mb-8">
        <div class="grid-list" v-if="fieldsDropdownList?.length > 0">
          <template v-for="item in fieldsDropdownList">
            <div class="title">
              <a-input allowClear class="w-full" v-model:value="item.origin"></a-input>
            </div>
            <div class="title">
              <a-select
                v-if="form?.type != 'FILE'"
                allowClear
                :options="computedOriginList"
                class="w-full"
                v-model:value="item.target"
              ></a-select>
              <a-input v-else v-model:value="item.target"></a-input>
            </div>
            <div class="title">
              <a-button danger @click="moveToRecycleBin(item.id)" v-if="form?.type !== 'FILE'">
                <DeleteOutlined />
              </a-button>
              <a-button danger @click="del(item.id)" v-else><DeleteOutlined /></a-button>
            </div>
          </template>
        </div>
        <div v-else class="w-full">
          <a-empty />
        </div>
      </div>
    </div>
    <a-divider></a-divider>
    <div class="center">
      <a-button-group>
        <a-button @click="prevStep">{{ t('Previous step') }}</a-button>
        <a-button @click="nextStep" type="primary">{{ t('Next step') }}</a-button>
      </a-button-group>
    </div>
  </div>
</template>

<script setup lang="ts">
import { fieldConfig } from '@/api/modules';
import { fieldsDropdownList } from '@/data/data';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { useCloned } from '@vueuse/core';
import { message, Modal } from 'ant-design-vue';
import type { DefaultOptionType } from 'ant-design-vue/es/select';
import { nanoid } from 'nanoid';
import type { DataConnectionForm, Fields } from '../types';

const { t } = useI18n();

const step = defineModel<number>('step');

const form = defineModel<DataConnectionForm>('form');

const recycleBin = ref<Fields[]>([]);

const nextStep = async () => {
  try {
    const { data } = await fieldConfig(fieldsDropdownList.value);
    if (data.code === '200' && form.value) {
      step.value!++;
      form.value.store.sunlux = data.data.sunlux;
    }
  } catch (error: any) {
    message.error(error.toString() || 'Failed to get field config');
  }
};
const cloneList = ref(useCloned(fieldsDropdownList.value).cloned.value);

const prevStep = () => {
  step.value = 1;
};
const moveToRecycleBin = (id: string) => {
  recycleBin.value.push(fieldsDropdownList.value.find(v => v.id === id)!);
  del(id);
};

const del = (id: string) => {
  fieldsDropdownList.value = fieldsDropdownList.value.filter(v => v.id !== id);
};
const clear = () => {
  Modal.warn({
    title: 'Warning',
    content: 'Are you sure you want to clear all fields?',
    onOk() {
      fieldsDropdownList.value = [];
    },
  });
};

const computedOriginList = computed((): DefaultOptionType[] => {
  return cloneList.value.map(v => {
    const findTarget = fieldsDropdownList.value.find(m => {
      if (v.target === m.target) {
        return true;
      }
      return false;
    })?.target;

    return {
      label: v.target,
      value: v.target,
      disabled: !!findTarget,
    };
  });
});
const addField = () => {
  fieldsDropdownList.value.push({
    origin: '',
    target: '',
    id: nanoid(),
  });
};
const recoverField = () => {
  if (recycleBin.value.length > 0) {
    fieldsDropdownList.value.push({
      ...recycleBin.value.pop()!,
    });
  }
};

onUnmounted(() => {
  if (form.value?.type !== 'FILE') {
    fieldsDropdownList.value = [];
  }
});
watch(fieldsDropdownList, () => {
  cloneList.value = useCloned(fieldsDropdownList.value).cloned.value;
});
</script>

<style lang="scss" scoped>
.fields {
  @apply w-[70%] mx-auto max-h-[60vh] overflow-auto;
}
.grid-list {
  max-height: 60vh;
  @apply grid grid-cols-3 overflow-auto mt-4 gap-4 mb-4;
}
.title {
  @apply w-full text-center text-16px;
}
</style>
